package com.service.single.annotation;


import com.service.single.exception.BizException;
import com.service.single.util.TokenUtil;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;

/**
 * 接口重复请求处理
 * 如果不是针对某个方法，可以直接将校验写到拦截器上
 */
@Aspect
@Component
public class RepeatRequestAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Before("execution(public *  com.service.single.controller.*.*(..)) && @annotation(RepeatRequest)")
    public void before() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String username = TokenUtil.parseJwt().get("loginName").asString();
        // 请求路径
        String path = request.getServletPath();
        String key = username + path;
        if (redisTemplate.hasKey(key)) {
            throw new BizException(HttpStatus.BAD_REQUEST.value(), "重复请求");
        }
        redisTemplate.opsForValue().set(key, path, Duration.ofSeconds(2L));
    }
}
